<template>
  <el-dialog
    v-model="visible"
    class="component-add-or-update"
    :title="!dataForm.id ? $t('sysManagement.add') : $t('sysManagement.modify')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') === 'English' ? '155px' : '110px'"
      @submit.prevent
      @keyup.enter="onSubmit(dataFormRef)"
    >
      <el-form-item
        :label="$t('sysManagement.type')"
        prop="type"
      >
        <el-radio-group v-model="dataForm.type">
          <el-radio
            v-for="(type, index) in dataForm.typeList"
            :key="index"
            :label="index"
          >
            {{
              type
            }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="dataForm.typeList[dataForm.type] + $t('publics.name')"
        prop="name"
      >
        <el-input
          v-model="dataForm.name"
          :placeholder="dataForm.typeList[dataForm.type] + $t('publics.name')"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="dataForm.typeList[dataForm.type] + $t('publics.en') + $t('publics.name')"
      >
        <el-input
          v-model="dataForm.nameEn"
          :placeholder="dataForm.typeList[dataForm.type] + $t('publics.en') + $t('publics.name')"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item :label="$t('sys.parentMenu')">
        <el-cascader
          v-model="selectedMenu"
          :options="menuList"
          change-on-select
          :props="menuListTreeProps"
          clearable
          @change="onSelectMenuChange"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.type === 1"
        :label="$t('sysManagement.menuRouter')"
        prop="url"
      >
        <el-input
          v-model="dataForm.url"
          :placeholder="$t('sysManagement.menuRouter')"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.type !== 0"
        :label="$t('sys.authorization')"
        prop="perms"
      >
        <el-input
          v-model="dataForm.perms"
          :placeholder="$t('sys.separated') + 'user:list,user:create'"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.type !== 2"
        :label="$t('hotSearch.seq')"
        prop="orderNum"
      >
        <el-input-number
          v-model="dataForm.orderNum"
          controls-position="right"
          :min="0"
          :label="$t('hotSearch.seq')"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.type !== 2"
        :label="$t('sys.isHidden')"
        prop="hidden"
      >
        <el-select
          v-model="dataForm.hidden"
          placeholder="请选择"
        >
          <el-option
            v-for="item in isHidden"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="dataForm.type !== 2"
        :label="$t('sys.menuIcon')"
        prop="icon"
      >
        <el-input
          ref="iconInputRef"
          v-model="dataForm.icon"
          :virtual-ref="iconListPopoverRef"
          :placeholder="$t('sys.menuIconName')"
          clearable
        />
        <el-popover
          ref="iconListPopoverRef"
          style="width: 390px"
          :virtual-ref="iconInputRef"
          placement="bottom-start"
          trigger="click"
          :popper-style="iconPopoverClass"
          virtual-triggering
        >
          <el-button
            v-for="(item, index) in iconList"
            :key="index"
            style="padding: 8px; margin: 8px 0 0 8px"
            :class="{ 'is-active': item === dataForm.icon }"
            @click="iconActiveHandle(item)"
          >
            <svg-icon
              :icon-class="`${item}`"
              style="stroke: #8a979e !important; color: #8a979e"
            />
          </el-button>
        </el-popover>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('coupon.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit(dataFormRef)"
        >
          {{ $t('coupon.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const iconInputRef = ref()
const iconListPopoverRef = ref()

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataForm = reactive({
  id: 0,
  type: 1,
  typeList: [$t('sys.catalog'), $t('sys.menu'), $t('sys.button')],
  name: '',
  nameEn: '',
  parentId: 0,
  url: '',
  perms: '',
  orderNum: 0,
  icon: '',
  iconList: [],
  hidden: 0
})

const isSubmit = ref(false)
const menuList = ref([])
const selectedMenu = ref([])
const menuListTreeProps = reactive({
  value: 'menuId',
  label: 'name',
  expandTrigger: 'hover',
  checkStrictly: true
})
const isHidden = [
  {
    label: $t('sys.yes'),
    value: 1
  },
  {
    label: $t('sys.no'),
    value: 0
  }
]

const iconPopoverClass = computed(() => {
  return {
    width: '396px'
  }
})

const iconList = []
// 加载图标
const onLoadIcons = () => {
  const icons = import.meta.glob('@/icons/svg/*.svg')
  for (const icon in icons) {
    const iconName = icon.split('/src/icons/svg/')[1].split('.svg')[0]
    iconList.push(iconName)
  }
}
onMounted(() => {
  onLoadIcons()
})
const dataFormRef = ref(null)
watch(
  () => dataForm.type,
  () => {
    dataFormRef.value.clearValidate()
  }
)
const init = id => {
  dataForm.id = id || 0
  isSubmit.value = false
  dataForm.nameEn = null
  http({
    url: http.adornUrl('/sys/menu/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    menuList.value = treeDataTranslate(data, 'menuId')
  }).then(() => {
    visible.value = true
    nextTick(() => {
      dataFormRef.value.resetFields()
    })
  }).then(() => {
    if (dataForm.id) {
      // 修改
      http({
        url: http.adornUrl(`/sys/menu/info/${dataForm.id}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.id = data.menuId
        dataForm.type = data.type
        dataForm.name = data.name
        dataForm.nameEn = data.nameEn
        dataForm.parentId = data.parentId
        dataForm.url = data.url
        dataForm.perms = data.perms
        dataForm.orderNum = data.orderNum
        dataForm.icon = data.icon
        dataForm.hidden = data.hidden ? 1 : 0
        selectedMenu.value = idList(menuList.value, data.parentId, 'menuId', 'children').reverse()
      })
    } else {
      selectedMenu.value = []
    }
  })
}
const onSelectMenuChange = val => {
  dataForm.parentId = val[val.length - 1]
}
// 图标选中
const iconActiveHandle = iconName => {
  dataForm.icon = iconName
}
// eslint-disable-next-line no-unused-vars
const validateUrl = (rule, value, callback) => {
  if (dataForm.type === 1 && !/\S/.test(value)) {
    callback(new Error($t('sys.menuUrlNoNull')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  name: [{ required: true, message: $t('sys.menuNameNoNull'), trigger: 'blur' }],
  url: [{ validator: validateUrl, required: true, trigger: 'blur' }]
})
// 表单提交
const onSubmit = async formEl => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      http({
        url: http.adornUrl('/sys/menu'),
        method: dataForm.id ? 'put' : 'post',
        data: http.adornData({
          menuId: dataForm.id || undefined,
          type: dataForm.type,
          name: dataForm.name,
          nameEn: dataForm.nameEn || dataForm.name,
          parentId: dataForm.parentId,
          url: dataForm.url,
          perms: dataForm.perms,
          orderNum: dataForm.orderNum,
          icon: dataForm.icon,
          hidden: dataForm.hidden
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit.value = false
      })
    }
  })
}
defineExpose({ init })
</script>
